import subprocess
import json


class LinuxHosts:

    def __init__(self, host, hostname=None, port=None, ssh_user='root', ssh_pass=None):
        self.host = host
        self.hostname = hostname
        self.port = port
        self.ssh_user = ssh_user
        self.ssh_pass = ssh_pass
        serverhostname = self.hostname
        with open('collogs/hostrunninglogs.json', 'r') as jsonfilenow:
            datajsonnow = json.load(jsonfilenow)
            if serverhostname not in datajsonnow["hostlist"]:
                # 初始化监控项
                datajsonnow["hostlist"][serverhostname] = {"hostip": "", "cpuusage": [], "memusage": []}
                print('jsonfile updated')
            with open('collogs/hostrunninglogs.json', 'w') as jsonfilenew:
               json.dump(datajsonnow, jsonfilenew, indent=2)

    def check_host_ping(self):
        # linux系统ping检测命令
        cmd = "ping {0} -c 3|grep ', 0% packet loss'|wc -l".format(self.host)
        process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out = str(process.stdout.read(), encoding='utf-8').strip()
        # err = process.stderr.read()
        if out == '1':
            return True
        else:
            return False

    def check_host_cpu_usage(self):
        cmd = "top -bn 3|grep 'Cpu'|awk '{print \\$2}'"
        cmd_args = "ssh {0} -p{1} \"{2}\"".format(self.host, self.port, cmd)
        # print(cmd_args)
        process = subprocess.Popen(cmd_args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out = process.stdout.read()
        #err = str(process.stderr.read(), encoding='utf-8').strip()
        #if err:
        #    print('error msg:' + err)
        cpuuselist = []
        cpuusage = str(out, encoding='utf-8').strip().strip('%').split('%')[0]
        for i in cpuusage.split("\n"):
            cpuuselist.append(i)
        cpuusage = max(cpuuselist)
        #print(cpuusage)

        serverhostname = self.hostname
        with open('collogs/hostrunninglogs.json', 'r') as jsonfile:
            newdatajson = json.load(jsonfile)
            newdatajson["hostlist"][serverhostname]["hostip"] = self.host
            newdatajson["hostlist"][serverhostname]['cpuusage'].append(cpuusage)
        if len(newdatajson["hostlist"][serverhostname]['cpuusage']) > 5:
            newdatajson["hostlist"][serverhostname]['cpuusage'].pop(0)
        with open('collogs/hostrunninglogs.json', 'w') as jsonfilenew:
            json.dump(newdatajson, jsonfilenew, indent=2)
        result = self.host + ' : ' + str(cpuusage)
        return result

    def check_host_mem_usage(self):
        cmd1 = "free -k|awk '{if (NR==2) print \\$2}'"
        cmd2 = "free -k|awk '{if (NR==2) print \\$3}'"
        cmd_args1 = "ssh {0} -p{1} \"{2}\"".format(self.host, self.port, cmd1)
        cmd_args2 = "ssh {0} -p{1} \"{2}\"".format(self.host, self.port, cmd2)
        process1 = subprocess.Popen(cmd_args1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        process2 = subprocess.Popen(cmd_args2, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out1 = process1.stdout.read()
        out2 = process2.stdout.read()
        err = str(process1.stderr.read(), encoding='utf-8').strip()
        if err:
            print('error msg:' + err)
        memtotal = str(out1, encoding='utf-8').strip()
        memusage = str(out2, encoding='utf-8').strip()
        memusageper = round(int(memusage) / int(memtotal) * 100, 2)
        #print(memusageper)
        serverhostname = self.hostname
        with open('collogs/hostrunninglogs.json', 'r') as jsonfile:
            newdatajson = json.load(jsonfile)
            newdatajson["hostlist"][serverhostname]["hostip"] = self.host
            newdatajson["hostlist"][serverhostname]['memusage'].append(memusageper)
        if len(newdatajson["hostlist"][serverhostname]['memusage']) > 5:
            newdatajson["hostlist"][serverhostname]['memusage'].pop(0)
        with open('collogs/hostrunninglogs.json', 'w') as jsonfilenew:
            json.dump(newdatajson, jsonfilenew, indent=2)
        result = self.host + ' : ' + str(memusageper)
        return result


# server = LinuxHosts("21.76.119.39", hostname='ansible', port='10022')
#vboxlinux.check_host_cpu_usage()
#vboxlinux.check_host_mem_usage()
